<?php
namespace app\backstage\logic;
use think\Db;
class BookRecom
{
    /*列表数据获取*/
    public function getList($params)
    {
        $field = 'create_date,nid,recharge_amount,clicks_num';

        $groupBy = '';
        if (request()->_role->alias == 'agent') {
            $type = 1;
            if(isset($params['channel_id']) && $params['channel_id'] > 0)
            {
                $type = 2;
            }
        }

        if (request()->_role->alias == 'channel') {
            $type = 2;
        }

        $condition[] = ['nid', 'eq', 'gt:0','nid'];

        $where   = buildQueryCondition($condition, $params);

        if (isset($params['field'])) {
            $orderBy = [$params['field'] => $params['order']];
        } else {
            $orderBy = ['id' => 'DESC'];
        }

        $BookRecom = \think\facade\App::model('BookRecom');
        $list = $BookRecom->getList($type, $where, $field, $params['page'], $params['limit'], $orderBy, $groupBy);

        $summary = ['clicks_num'=>0,'recharge_amount'=>0,'click_avg'=>0];

        if ($list) {

            $nid_gh = array_unique(array_column($list,'nid'));
            $novels = Db::table('novel')->where('id','in',$nid_gh)->column('id,title,son_class_id');

            foreach ($list as $k => $v) {
                $list[$k]['bookname'] = isset($novels[$v['nid']]) ? $novels[$v['nid']]['title'] : '';
                $list[$k]['click_avg'] = $v['recharge_amount'] > 0 ? round($v['recharge_amount']/$v['clicks_num']/100,2) : 0;
            }

            $recharge_amount = array_sum(array_column($list,'recharge_amount'));
            $clicks_num = array_sum(array_column($list,'clicks_num'));

            $summary['click_avg'] = $recharge_amount > 0 ? round($recharge_amount/$clicks_num/100,2) : 0;
            $summary['recharge_amount'] = $recharge_amount > 0 ? round($recharge_amount/100,2) : 0;
            $summary['clicks_num'] = $clicks_num;

        }

        $result['count'] = $BookRecom->getTotalNumber($type, $where, $groupBy);
        $result['list']  = $list;
        $result['summary'] = $summary;

        return $result;
    }
}